﻿ ############################################################################
 #  Copyright Huang Jian 2008
 #
 #  Licensed under the Apache License, Version 2.0 (the "License");
 #  you may not use this file except in compliance with the License.
 #  You may obtain a copy of the License at
 #
 #      http://www.apache.org/licenses/LICENSE-2.0
 #
 #  Unless required by applicable law or agreed to in writing, software
 #  distributed under the License is distributed on an "AS IS" BASIS,
 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 #  See the License for the specific language governing permissions and
 #  limitations under the License.
 #
 ############################################################################

 ############################################################################
 #  Get client ip location by its ip address
 #  This file as a proxy server to bypass cross domain issue
 #  
 #  Thank to Bart Van, i learn this technoloy from his masterpiece:
 #  Ajax Cross Domain, http://www.ajax-cross-domain.com/
 #
 #  Also thanks to GaoJiaWang, he teach me how to use app engine and
 #  lend this website to me.
 #
 ############################################################################

import cgi
import os
from google.appengine.api import urlfetch 

client_ip = cgi.escape(os.environ["REMOTE_ADDR"])
url = "http://www.ip.cn/?q=" + client_ip

### a chinese unicode take place 3 bytes,
### so it's a html escaped string, not unicode string,
### so we find ascii letters
### search example: 
###       您要查询的IP地址为：202.106.180.68<br>查询结果为：北京市Google中国\n<br />
try:
  html = urlfetch.fetch(url)
except IOError:
  client_address = ""
else:
  try:
    start_pos = html.content.index("<br>", 1400);
    start_pos += 22
    end_pos = html.content.index("<br />", start_pos);
    end_pos -=2
  except ValueError:
    client_address = ""
  else:
    client_address = html.content[start_pos:end_pos]

print 'application/x-javascript'
print ''

print "var MyClient = new Object();"
print "MyClient.ipAddress = '" + client_ip + "';"
print "MyClient.ipLocation = '" + client_address + "';"